package com.yonyou.iuap.ipaas.connector.sdwcoatencent.internal;

import cn.hutool.core.lang.Validator;
import com.yonyou.iuap.ipaas.cache.api.Consistency;
import com.yonyou.iuap.ipaas.cache.core.CacheContext;
import com.yonyou.iuap.ipaas.cache.core.CacheService;
import com.yonyou.iuap.ipaas.connector.sdk.api.model.ConnectorParams;
import com.yonyou.iuap.ipaas.connector.sdk.internal.connection.CoreConnection;
import com.yonyou.iuap.ipaas.connector.sdwcoatencent.internal.utils.ApiUtil;
import com.yonyou.yonlinker.ysb.runtime.api.connection.ConnectionValidationResult;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Objects;

/**
 * 此类表示扩展连接
 */
@Getter
public final class SdwcoatencentConnection implements CoreConnection {

    private static Logger logger = LoggerFactory.getLogger(SdwcoatencentConnection.class);
    
    public static final CacheService cacheService = CacheService.getCacheService();
    
    private String host;
    
    private Long agentid;
    
    private String corpid;
    
    private String appCorpsecret;
    
    private String connectCorpsecret;
    
    private Integer httpTimeOut;
    
    private ConnectorParams params;
    
    private String authInterface;
    
    private String authHost;

    /**
     * 构造函数
     *
     * @param params
     */
    public SdwcoatencentConnection(ConnectorParams params) {
        this.params = params;
        initConnection(params);
    }

    @Override
    public void initConnection(ConnectorParams params) {
        this.host = (String)params.getParams().get("host");
        this.appCorpsecret = (String)params.getParams().get("appCorpsecret");
        this.connectCorpsecret = (String)params.getParams().get("connectCorpsecret");
        this.corpid = (String)params.getParams().get("corpid");
        this.agentid = Long.valueOf(Long.parseLong((String)params.getParams().get("agentid")));
        this.httpTimeOut = Integer.valueOf(Integer.parseInt((String)params.getParams().get("httpTimeOut")));
        this.authInterface = (String)params.getParams().get("authInterface");
        this.authHost = (String)params.getParams().get("authHost");
    }

    @Override
    public void invalidate() {
        //此处可以写一些处理断开连接后的事项代码；
        String cacheKey = "token:" + corpid;
        cacheService.evict(cacheKey);
        logger.error("【企微连接器】accessToken已清除");
    }

    @Override
    public ConnectionValidationResult validate() {
        try {
            if (!Validator.isUrl(this.host))
                return ConnectionValidationResult.failure("Connection failed, host needs to be prefixed with https or http", null);
            if (!Validator.isUrl(this.authHost))
                return ConnectionValidationResult.failure("Connection failed, authHost needs to be prefixed with https or http", null);
            if (StringUtils.isNotBlank(this.authInterface) && !Validator.isUrl(this.authInterface))
                return ConnectionValidationResult.failure("Connection failed, authInterface needs to be prefixed with https or http", null);
            if (StringUtils.isBlank(this.appCorpsecret) && StringUtils.isBlank(this.connectCorpsecret))
                return ConnectionValidationResult.failure("AppCorpsecret and connectCorpsecret cannot be empty at the same time", null);
            // String corpsecret = StringUtils.isNotBlank(this.appCorpsecret) ? this.appCorpsecret : this.connectCorpsecret;
            // Object token = AuthService.refreshToken(this.corpid, corpsecret, this.host, this.httpTimeOut);
            String token = ApiUtil.getAccessToken(this.corpid,this.host,this.appCorpsecret,this.httpTimeOut);
            // System.out.println(token);
            if (Objects.isNull(token))
                return ConnectionValidationResult.failure("validate connection failed ", null);
        } catch (Exception e) {
            return ConnectionValidationResult.failure("validate connection failed ", e);
        }
        return ConnectionValidationResult.success();
    }
    
    static {
        CacheContext cacheContext = new CacheContext();
        cacheContext.setPushMessage(false);
        cacheContext.setConsistency(Consistency.strict);
        cacheContext.setRunPolicy("redis");
        cacheContext.setConnectorMainClass(SdwcoatencentExtension.class);
        CacheService.initContext(cacheContext);
    }

}
